from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from flask import Flask, jsonify, request
from fake_useragent import FakeUserAgent
from selenium.webdriver.firefox.service import Service

app = Flask(__name__)


@app.route('/xxw', methods=['GET'])
def get_data():
    # 获取请求参数中的编号
    # code = request.args.get('code')
    code = 'AVPB5V2GXYUBLVUQ'
    if not code:
        return jsonify({'error': 'Missing "code" parameter'}), 400

    ua = FakeUserAgent()
    user_agent = ua.firefox  # 获取一个模拟的Firefox浏览器的User-Agent
    options = webdriver.FirefoxOptions()
    options.headless = True
    options.add_argument('--headless')
    options.add_argument(f'--user-agent="{user_agent}"')
    # 请替换为你实际的 GeckoDriver 路径
    geckodriver_path = '/Users/lidongxiao/Downloads/geckodriver'
    service = Service(geckodriver_path)
    bro = webdriver.Firefox(options=options,service=service)
    try:
        bro.get('https://www.chsi.com.cn/xlcx/bgcx.jsp')
        # 使用显式等待查找输入框
        input_box = WebDriverWait(bro, 10).until(
            EC.presence_of_element_located(
                (By.XPATH, '/html/body/div[3]/div/div[2]/div[2]/div[1]/form/div/div[2]/input'))
        )
        input_box.send_keys(code)

        # 使用显式等待查找查询按钮并点击
        check_btn = WebDriverWait(bro, 10).until(
            EC.element_to_be_clickable(
                (By.XPATH, '//*[@id="app"]/div[2]/div[2]/div[1]/form/div/div[3]/button'))
        )
        check_btn.click()

        # 使用显式等待等待结果元素加载
        content = WebDriverWait(bro, 10).until(
            EC.presence_of_all_elements_located(
                (By.XPATH, '/html/body/div[2]/div/div[4]/div[2]/div/div[3]/div/div[2]/div'))
        )
        arr = []
        for li in content:
            if li.text:
                content_text = li.text.replace('\n', '=')
                data = {'work': content_text}
                arr.append(data)

        return jsonify(arr), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500
    finally:
        # 确保浏览器资源被释放
        bro.quit()


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3000, debug=True)
